﻿#region
using System.Linq;
using System.Xml.Linq;

#endregion

namespace MidnightPeach.EdmxTransformer
{
    public static class EdmxSchemaExtension
    {
        public static EdmxSchema Schema { get; set; }

        public static Mapper Mapper { get; set; }

        public static void ReplaceEntity(this XAttribute attribute, bool usePluralForm = false)
        {
            string entityFrom = Mapper[attribute.Value.GetLastDottedPart(), usePluralForm];

            var tokens = attribute.Value.Split('.');

            var entityTo = Schema.GetEntityName(entityFrom, usePluralForm);
            if (tokens.Length > 1)
                entityTo = string.Join(".", tokens.Take(tokens.Length - 1)) + "." + entityTo;
//                entityTo = tokens[0] + "." + entityTo;

            attribute.Value = entityTo;
        }

        public static void ReplaceProperty(this XAttribute attribute, string entityTo)
        {
            var entityFrom = Mapper[entityTo];
            var @from = Mapper[entityTo, attribute.Value];
            
            attribute.Value = Schema.GetPropertyName(entityFrom, @from);
        }

        public static void ReplaceNavigation(this XAttribute attribute, string relationship, string fromRole, string toRole)
        {
            attribute.Value = Schema.GetNavigationName(relationship, fromRole, toRole);
        }
    }
}